package com.delistry.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.delistry.ConsoleProcess;
import com.delistry.LoginController;
import com.delistry.server.model.DeliverManager;

public class ServiceServer extends Thread {
	private static ServiceServer _instance;// server instance
	private ServerSocket _serverSocket;// server connection
	private int _port = 9000; // port
	@SuppressWarnings("unused")
	private LoginController _loginController;

	public static ServiceServer getInstance() {
		if (_instance == null) {
			_instance = new ServiceServer();			
		}
		return _instance;
	}

	public ServiceServer() {
		super("GameServer");		
	}

	@Override
	public void run() {
		
		while (true) {
			System.out.println("wait for connection...");
			try {
				Socket socket = null;
				synchronized(_serverSocket){
					socket = _serverSocket.accept();
				}
				String host = socket.getInetAddress().getHostAddress();
				if (host == "isBanned") { // invalid connection

				} else {
					// valid connection
					ClientProcess client = new ClientProcess(socket);
					GeneralThreadPool.getInstance().execute(client);
				}
			} catch (IOException ioexception) {
				ioexception.printStackTrace();
			}
		}
	}

	/** Initialize Server Instance */
	public void initialize() throws Exception {
		/** Initialize Server Connection */
		_serverSocket = new ServerSocket(_port);
		System.out.println("Server has been built up at port: " + _port);

		_loginController = LoginController.getInstance();
		// Initialize World
		DeliverManager.getInstance();

		System.out.println("Server Initialize, - Done.");
		// command line
		Thread cp = new ConsoleProcess();
		cp.start();
		this.start();
	}

}